package com.zhongshengnetwork.rightbe.letter.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.dbmodel.LetterdbModel;
import com.zhongshengnetwork.rightbe.keyboard.SimpleCommonUtils;
import com.zhongshengnetwork.rightbe.keyboard.adapter.ChattingListAdapter;
import com.zhongshengnetwork.rightbe.keyboard.data.ImMsgBean;
import com.zhongshengnetwork.rightbe.keyboard.utils.ImageLoadUtils;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.letter.activity.ChatViewActivity;
import com.zhongshengnetwork.rightbe.letter.holder.TextMsgViewHolder;
import com.zhongshengnetwork.rightbe.letter.holder.TimeMsgViewHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.imlib.model.Conversation;
import sj.keyboard.utils.imageloader.ImageBase;

/**
 * Created by zhongsheng-luojianlan on 16/10/22.
 */

public class ChatViewAdapter extends BaseAdapter implements View.OnClickListener, View.OnLongClickListener{
    public Map<String,String> headerMap = null;
    public Map<String,String> nameMap = null;
    public List<LetterdbModel> mData = null;
    private ChatViewActivity mActivity;
    //item的最小宽度
    private int mMinWidth;
    //item的最大宽度
    private int mMaxWidth;
    //public Conversation.ConversationType conversationType;

    public ChatViewAdapter(ChatViewActivity activity){
        if (mData == null){
            mData = new ArrayList<LetterdbModel>();
        }
        if (headerMap == null){
            headerMap = new HashMap<String, String>();
        }
        if (nameMap == null){
            nameMap = new HashMap<String, String>();
        }
        mActivity = activity;
        //获取屏幕的宽度
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        //最大宽度为屏幕宽度的百分之七十
        mMaxWidth = (int) (outMetrics.widthPixels * 0.7f);
        //最大宽度为屏幕宽度的百分之十五
        mMinWidth = (int) (outMetrics.widthPixels * 0.15f);
    }

    public void addData(LetterdbModel chatData){
        if (chatData == null){
            return;
        }
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(chatData);
        this.notifyDataSetChanged();
    }

    public void setUserInfo(String userid, String header, String name){
        if (CommonUtils.isEmpty(userid) || CommonUtils.isEmpty(header) || CommonUtils.isEmpty(name)){
            return;
        }
        if (headerMap == null){
            headerMap = new HashMap<String, String>();
        }
        if (nameMap == null){
            nameMap = new HashMap<String, String>();
        }
        headerMap.put(userid,header);
        nameMap.put(userid,name);
    }

    public void addDataList(List<LetterdbModel> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        if (mData == null) {
            mData = new ArrayList<>();
        }
        //Collections.reverse(data);   //这行就是将list的内容反转，下面再装进adapter里，就可以倒序显示了
        for (LetterdbModel chatData : data) {
            mData.add(chatData);
        }
        this.notifyDataSetChanged();
    }

    public void insertDataList(List<LetterdbModel> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        if (mData == null) {
            mData = new ArrayList<>();
        }
        //Collections.reverse(data);   //这行就是将list的内容反转，下面再装进adapter里，就可以倒序显示了
        for (LetterdbModel chatData : data) {
            mData.add(0,chatData);
        }
        this.notifyDataSetChanged();
    }

    public void clearData(){
        if (mData == null || mData.size() <= 0){
            return;
        }
        mData.clear();
        this.notifyDataSetChanged();
    }

    public void updateData(int position, LetterdbModel chatData){
        if (mData == null || mData.size() <= position){
            return;
        }
        mData.set(position,chatData);
        this.notifyDataSetChanged();
    }

    public int getCurrentCount(){
        if (mData == null){
            mData = new ArrayList<>();
            return 0;
        }
        return mData.size();
    }

    public LetterdbModel getIndexData(int index){
        if (index <0 || mData == null || index >= mData.size()){
            return null;
        }
        return mData.get(index);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public boolean isEnabled(int position) {
        // TODO Auto-generated method stub
        return super.isEnabled(position);
    }

    @Override
    public int getItemViewType(int position) {
        if (mData.get(position) == null) {
            return -1;
        }
        LetterdbModel chatData = mData.get(position);
        switch (chatData.getType()){
            case LetterConstant.sx_timeMsg:
                return LetterConstant.xiaoHuiTiaoLayoutType;
            case LetterConstant.sx_unDefineMsg:
                return LetterConstant.xiaoHuiTiaoLayoutType;
            case LetterConstant.sx_textMsg:
                return LetterConstant.textMsgLayoutType;
            default:
                return LetterConstant.xiaoHuiTiaoLayoutType;
        }
    }

    @Override
    public int getViewTypeCount() {
        return LetterConstant.viewLayoutTypeCount;
    }


    /**
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final LetterdbModel chatData = mData.get(position);
        int type = getItemViewType(position);
        View holderView = null;
        switch (type) {
            case LetterConstant.textMsgLayoutType://文本消息
                TextMsgViewHolder textMsgViewHolder;
                if (convertView == null) {
                    textMsgViewHolder = new TextMsgViewHolder();
                    holderView = LayoutInflater.from(mActivity).inflate(R.layout.text_msg_view, null);
                    holderView.setFocusable(true);
                    textMsgViewHolder.right_avatar = (ImageView) holderView.findViewById(R.id.text_right_avatar);
                    textMsgViewHolder.right_content = (TextView) holderView.findViewById(R.id.text_right_content);
                    textMsgViewHolder.right_state = (ImageView) holderView.findViewById(R.id.state_text);
                    textMsgViewHolder.right_click = (TextView) holderView.findViewById(R.id.text_right_click);
                    textMsgViewHolder.right_layout = (RelativeLayout) holderView.findViewById(R.id.text_right_content_layout);
                    textMsgViewHolder.left_avatar = (ImageView) holderView.findViewById(R.id.text_left_avatar);
                    textMsgViewHolder.left_content = (TextView) holderView.findViewById(R.id.text_left_content);
                    textMsgViewHolder.name = (TextView) holderView.findViewById(R.id.text_name);
                    textMsgViewHolder.left_click = (TextView) holderView.findViewById(R.id.text_left_click);
                    textMsgViewHolder.left_layout = (RelativeLayout) holderView.findViewById(R.id.text_left_content_layout);
                    holderView.setTag(textMsgViewHolder);
                    convertView = holderView;
                } else {
                    textMsgViewHolder = (TextMsgViewHolder) convertView.getTag();
                }

                if (chatData.getIsSelf() == 1){//自己发送的消息
                    textMsgViewHolder.left_avatar.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.left_content.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.left_layout.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.name.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.left_click.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.right_avatar.setVisibility(View.VISIBLE);
                    textMsgViewHolder.right_content.setVisibility(View.VISIBLE);
                    textMsgViewHolder.right_click.setVisibility(View.VISIBLE);
                    textMsgViewHolder.right_layout.setVisibility(View.VISIBLE);
                    Glide.with(CustomApplication.mContext).load(headerMap.get(chatData.getUserid())).transform(new CircleTransform(CustomApplication.mContext)).dontAnimate().into(textMsgViewHolder.right_avatar);
                    textMsgViewHolder.right_click.setClickable(true);
                    textMsgViewHolder.right_click.setTag(position);
                    textMsgViewHolder.right_click.setOnClickListener(this);
                    if (chatData.getState() == LetterConstant.sx_normal_state){
                        textMsgViewHolder.right_state.clearAnimation();
                        textMsgViewHolder.right_state.setVisibility(View.INVISIBLE);
                    }else if(chatData.getState() == LetterConstant.sx_sending_state){
                        textMsgViewHolder.right_state.setVisibility(View.VISIBLE);
                        textMsgViewHolder.right_state.setImageResource(R.mipmap.sending);
                        Animation mAnimation = AnimationUtils.loadAnimation(this.mActivity, R.anim.roraterepeat);
                        textMsgViewHolder.right_state.startAnimation(mAnimation);
                    }else {
                        textMsgViewHolder.right_state.clearAnimation();
                        textMsgViewHolder.right_state.setVisibility(View.VISIBLE);
                        textMsgViewHolder.right_state.setImageResource(R.mipmap.resent);
                        textMsgViewHolder.right_state.setTag(position);
                        textMsgViewHolder.right_state.setClickable(true);
                        textMsgViewHolder.right_state.setOnClickListener(this);
                    }
                    mActivity.registerForContextMenu(textMsgViewHolder.right_content);
                    textMsgViewHolder.right_content.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                        @Override
                        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                            menu.add(0,0,0,"添加");
                            menu.add(0,1,0,"删除");
                            menu.add(0,2,0,"删除ALL");
                        }
                    });

                }else {//接收到的消息
                    textMsgViewHolder.left_avatar.setVisibility(View.VISIBLE);
                    textMsgViewHolder.left_content.setVisibility(View.VISIBLE);
                    textMsgViewHolder.name.setVisibility(View.VISIBLE);
                    textMsgViewHolder.left_click.setVisibility(View.VISIBLE);
                    textMsgViewHolder.left_layout.setVisibility(View.VISIBLE);
                    textMsgViewHolder.right_avatar.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.right_content.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.right_state.clearAnimation();
                    textMsgViewHolder.right_state.setVisibility(View.GONE);
                    textMsgViewHolder.right_click.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.right_layout.setVisibility(View.INVISIBLE);
                    textMsgViewHolder.name.setText(nameMap.get(chatData.getFromuserid()));
                    Glide.with(CustomApplication.mContext).load(headerMap.get(chatData.getFromuserid())).transform(new CircleTransform(CustomApplication.mContext)).dontAnimate().into(textMsgViewHolder.left_avatar);
                    textMsgViewHolder.left_click.setTag(position);
                    textMsgViewHolder.left_click.setClickable(true);
                    textMsgViewHolder.left_click.setOnClickListener(this);
                    textMsgViewHolder.left_click.setOnLongClickListener(this);
                    mActivity.registerForContextMenu(textMsgViewHolder.left_content);
                    textMsgViewHolder.left_content.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                        @Override
                        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                            menu.add(0,0,0,"添加");
                            menu.add(0,1,0,"删除");
                            menu.add(0,2,0,"删除ALL");
                        }
                    });
                }
                disPlayTextView(position,holderView,textMsgViewHolder,chatData);
                break;

            case LetterConstant.xiaoHuiTiaoLayoutType:
                TimeMsgViewHolder timeMsgViewHolder;
                if (convertView == null){
                    timeMsgViewHolder = new TimeMsgViewHolder();
                    holderView = LayoutInflater.from(mActivity).inflate(R.layout.xiaohuitiao_msg_view, null);
                    timeMsgViewHolder.time = (TextView) holderView.findViewById(R.id.xiaohuitiao_msg_view_content);
                    holderView.setTag(timeMsgViewHolder);
                    convertView = holderView;
                }else {
                    timeMsgViewHolder = (TimeMsgViewHolder) convertView.getTag();
                }
                SimpleCommonUtils.spannableEmoticonFilter(timeMsgViewHolder.time, chatData.getExtra());
                break;


            default:
                convertView = new View(mActivity);
                break;
        }

        return convertView;
    }


    public void disPlayTextView(int position, View view, TextMsgViewHolder holder, LetterdbModel chatData) {
        if (chatData.getIsSelf() == 1){
            SimpleCommonUtils.spannableEmoticonFilter(holder.right_content, chatData.getContent());
        }else {
            SimpleCommonUtils.spannableEmoticonFilter(holder.left_content, chatData.getContent());
        }
    }

    public void disPlayLeftImageView(int position, View view, ChattingListAdapter.ViewHolderLeftImage holder, ImMsgBean bean) {
        try {
            if (ImageBase.Scheme.FILE == ImageBase.Scheme.ofUri(bean.getImage())) {
                String filePath = ImageBase.Scheme.FILE.crop(bean.getImage());
                Glide.with(holder.iv_image.getContext())
                        .load(filePath)
                        .dontAnimate().into(holder.iv_image);
            } else {
                ImageLoadUtils.getInstance(mActivity).displayImage(bean.getImage(), holder.iv_image);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public final class ViewHolderLeftImage {
        public ImageView iv_avatar;
        public ImageView iv_image;
    }

    public void onClick(View view){
        //头像点击事件
        //System.out.print(view.getTag()+":头像点击事件\n");
//        if (conversationType == Conversation.ConversationType.CUSTOMER_SERVICE){
//            return;
//        }
        if (view instanceof TextView){
            int position = (int)view.getTag();
            LetterdbModel chatData = mData.get(position);
            //进入个人主页
            Intent intent = new Intent(mActivity, UserLangActivity.class);
            if (chatData.getIsSelf() == 1){
                intent.putExtra(APIKey.useridKey,chatData.getUserid());
                intent.putExtra(APIKey.titleKey,CustomApplication.loginModel.getNickname());
            }else {
                intent.putExtra(APIKey.useridKey,chatData.getFromuserid());
                intent.putExtra(APIKey.titleKey,chatData.getNickname());
            }
            intent.putExtra(APIKey.typeKey,1);
            mActivity.startActivity(intent);
        }else if (view instanceof  ImageView){
            int position = (int)view.getTag();
            LetterdbModel chatData = mData.get(position);
            if (chatData != null){
                chatData.setState(LetterConstant.sx_sending_state);
                mData.set(position,chatData);
                notifyDataSetChanged();
                mActivity.resendMessage(chatData, position);
            }

        }


    }

    public boolean onLongClick(View view){
//        if (conversationType == Conversation.ConversationType.CUSTOMER_SERVICE){
//            return true;
//        }
        //????
        /*
        if (mActivity.conversationType == Conversation.ConversationType.GROUP){
            int position = (int)view.getTag();
            LetterdbModel chatData = mData.get(position);
            if (chatData.isFromSelf() == false){
                if (!chatData.getUserId().equals(CustomApplication.loginModel.getUid())){
                    mActivity.atUser(chatData.getUserId(),nameMap.get(chatData.getUserId()));
                }

            }
        }
        */
        return true;
    }

}
